import {Link} from 'react-router-dom';
import {Select, Alert, Input, Modal, Form, Row, Col, Table, Breadcrumb, Icon,Upload ,Button,DatePicker} from 'antd';

const Option = Select.Option;
const FormItem = Form.Item;
import AppService from './../../common/utils/app.service'
import * as Actions from './actions'
import Utils from './../../common/utils/utils'
import * as CONSTANTS from './../../common/utils/constants'
import UploadImage from "./../../common/utils/app.service";
import axios from 'axios'
var Delta = require('quill-delta/lib/delta');
import ReactQuill, {Quill, Mixin, Toolbar} from 'react-quill'
import Moment from 'moment'

const modules = {
    toolbar: {
        container: [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
            ['blockquote', 'code-block'],

            [{'list': 'ordered'}, {'list': 'bullet'}],
            [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
            [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
            // [{ 'direction': 'rtl' }],                         // text direction

            [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
            [{'header': [1, 2, 3, 4, 5, 6]}],

            [{'color': []}, {'background': []}],          // dropdown with defaults from theme
            [{'font': []}],
            [{'align': []}],
            ['link', 'image'],
            // ['video'],
            ['clean']
        ],
        handlers: {
            "image": function () {
                let fileInput = this.container.querySelector('input.ql-image[type=file]');
                if (fileInput == null) {
                    fileInput = document.createElement('input');
                    fileInput.setAttribute('type', 'file');
                    fileInput.setAttribute('accept', 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
                    fileInput.classList.add('ql-image');
                    fileInput.addEventListener('change', () => {
                        if (fileInput.files != null && fileInput.files[0] != null) {
                            var formData = new FormData();
                            formData.append("upfile", fileInput.files[0]);
                            formData.append("withStatus", true);
                            axios.post(UploadImage.uploadImgUrl, formData, {
                                headers: {
                                    'Content-Type': 'multipart/form-data'
                                },
                                responseType: 'json'
                            }).then(res => {
                                if (res.data.errorCode == 0) {
                                    let range = this.quill.getSelection(true);
                                    this.quill.updateContents(new Delta()
                                        .retain(range.index)
                                        .delete(range.length)
                                        .insert({image: res.data.body})
                                        , Quill.sources.USER);
                                } else {
                                    console.error(res.data);
                                }
                            }).catch(e => {
                                console.error(e);
                            });
                        }
                    });
                    this.container.appendChild(fileInput);
                }
                fileInput.click();
            }
        }
    }
}

class SingerDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      detail:[],
        fileList: [],
        previewVisible: false,
        previewImage: '',

        newList:[
            {
                id:0,
                name:'否'
            },
            {
                id:1,
                name:'是'
            }
        ],
        startValue: null,
        endValue: null,
        endOpen: false,
        content:'',
        songTypeList: [],
    }
  }

    pictureChange = ({ fileList }) => {

        this.setState({ fileList });
        console.log(fileList)
    }

    componentWillMount(){
        // let _this = this;
        // Actions.getSongTypeList().then((result) => {
        //     if(result.errorCode === 0) {
        //         this.setState({
        //             songTypeList: result.body
        //         });
        //     }else {
        //         Utils.dialog.error(result.msg)
        //     }
        // });


    }

  componentDidMount() {
    let _this = this, {dispatch, match} = this.props, id = match.params.id;
       location.hash.indexOf('detail') > 0 && _this.getDateils(id);
      //_this.getDateils(id);
    console.log('detail',this.props);


  }

  getDateils = (id) => {
      let _this = this;
    Actions.getPlayRecordDetail(id).then(response => {
      if (response.errorCode === 0) {
          let fileList = _this.state.fileList;
          let fileList1 = _this.state.fileList1;
          fileList.push({

          });
          let detail=[];
          detail.push(response.body)
          
         console.log(detail,'detail')

          this.setState({
            detail:detail
        })
      }
    })
  };
    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }
    handleCancel = ()=>{
        this.setState({
            previewVisible: false
        })
    }
    handleSubmit = (e) => {
        e.preventDefault();
        let _this = this , { history} = this.props;


        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                console.log('Received values of form: ', values);
                _this.setState({buttonLoading: true})
                let params = values;
                //debugger
                params.cover = params.cover.file ? params.cover.file.response.body : params.cover;
                // params.isRecommend = parseInt(params.isRecommend.key) == 1 ? true : false;

                _this.props.match.params.id ? _this.updateInformation(params) : _this.addInformation(params)
            }
        });
    }

    addInformation = (params)=>{
        let _this = this , { history} = this.props;
        Actions.addInformation(params).then((res)=>{
            console.log('eeeee')
            console.log(res);
            _this.setState({buttonLoading: false})
            Utils.dialog.success('新增成功',()=>{
                history.push('/information/manager/index')
            });

        })
    };

    updateInformation = (params)=>{
        let _this = this , {history, match} = this.props;
        params.id = match.params.id;
        Actions.updateInformation(params).then((res)=>{
            console.log(res);
            _this.setState({buttonLoading: false})

            Utils.dialog.success('更新成功',()=>{
                history.push('/information/manager/index')
            });

        })
    }



    onChange = (field, value) => {
        this.setState({
            [field]: value,
        });
    }



    // 上传图片之前
  beforeUpload(file) {
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
      Utils.dialog.error('图片大小不能超过2MB!');
    }
    return isLt2M;
  }

  // 图片改变
  shandleChange = (prop, {file, fileList}) => {
    if (file.response && file.response.errorCode === 0) {
      let detail = this.state.detail
      detail[prop] = file.response.body
      this.setState({detail})
    } else if (file.response && file.response.errorCode != 0) {
      Utils.dialog.error(file.response.msg)
    }
  }
  
  // 上传图片时，转换返回的数据
  normFile = (e) => {
    let fileList = e.fileList.filter((file) => {
      if (file.response) {
        if (file.response.errorCode === 0) {
          file.url = file.response.body
          return true;
        }
      }
      return true;
    }).slice(-1);
    return fileList[0].url;
  }

  // 富文本编辑器内容改变
  handleEditorChange = (value) => {
    this.setState({
      content: value
    })
  }


  render() {
    const {match} = this.props;
       const { getFieldDecorator } = this.props.form;
    const {detail ,fileList,previewVisible, previewImage,newList} = this.state
      const uploadButton = (
          <div>
              <Icon type="plus" />
              <div className="ant-upload-text">Upload</div>
          </div>
      );
      const columns = [
     
        {
            title: "用户A昵称",
            dataIndex: "useraName",
            key: "useraName"
          },
          {
            title: "用户A分数",
            dataIndex: "useraScore",
            key: "useraScore"
          },
         
    
    
          {
            title: "用户B昵称",
            dataIndex: "userbName",
            key: "userbName",
           
          },
          {
            title: "用户B分数",
            dataIndex: "userbScore",
            key: "userbScore"
          },
         
          {
            title: "对战开始时间",
            dataIndex: "createTime",
            key: "createTime",
            render(endTime) {
              return Utils.formatDate(endTime, 'YYYY-MM-DD hh:ii')
            }
          },
          
          {
            title: "对战结束时间",
            dataIndex: "endTime",
            key: "endTime",
            render(endTime) {
              return Utils.formatDate(endTime, 'YYYY-MM-DD hh:ii')
            }
          },

       
    ]
     
     





    return (
      <div id="wrap">
        <Breadcrumb className="breadcrumb">
          <Breadcrumb.Item>
            <Link to={`/playRecord/manager/index`}>
              
              <span>对战记录列表</span>
            </Link>
          </Breadcrumb.Item>
          <Breadcrumb.Item>
              {location.hash.indexOf('detail') > 0 ? '对战详情' : ''}
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="content">


        <Table columns={columns}
                 rowKey='id'
                 dataSource={this.state.detail}
                 pagination={this.state.pagination}
                 loading={this.state.loading}
                 onChange={this.handleTableChange}
              
          />
        </div>
      </div>
    )

  }
}
const Detail = Form.create()(SingerDetail)
export default Detail